<?php
/**
 * 投注返奖执行脚本
 */
include_once 'common.php';
echo '<pre>';
// 获取所有中奖，但是未返奖的投注项数据
$sql  = 'SELECT item.`id`, item.`o_id`, item.`cn_play`, item.`en_play`, item.`betting_no`,
                item.`num`, item.`multiple`, item.`money_unit`, item.`eo_money`, item.`odds`, 
                main.`uid`, main.`order_no`, main.`lott_id`
        FROM ' . $dbprefix . 'lottery_order_item AS item
        LEFT JOIN ' . $dbprefix . 'lottery_order_main AS main
        ON item.`o_id` = main.`id`
        WHERE item.`winner` = 2 AND item.`prize_status` = 1 ORDER BY item.`id` DESC';
$list = getList($sql, $db);
if (!$list){
    echo 'NO Data';
    return;
}
// 查询所有彩种信息， 以便检查不同类型的投注来调用不同的计算中奖方法
$sql = 'SELECT cate.`sname`, lott.`id`, lott.`title` FROM ' . $dbprefix . 'lottery AS lott
        LEFT JOIN ' . $dbprefix . 'lottery_category AS cate
        ON lott.`cate_id` = cate.`id`';
$lottList  = getList($sql, $db);
$lottIdKey = array();
foreach ($lottList as $k => $v){
    $lottIdKey[$v['id']] = $v;
}

// 投注项整理为以订单为单位结构
$orderData = array();
foreach ($list as $k => $v){
    $orderData[$v['o_id']][] = $v;
}
// 检查符合要求的投注项，进行返奖计算
foreach ($orderData as $key => $value){
    $orderPrize = 0;
    foreach ($value as $k => $v){
        // 计算中奖金额，准备返奖[投注数量 * 赔率 * 投注金额单位 * 倍数 * 每注金额 ]
//         $winnerMoney    = $v['num'] * $v['odds'] * $v['money_unit'] * $v['multiple'] * $v['eo_money'];
        $lottTypeKey    = $lottIdKey[$v['lott_id']]['sname'];
        if ($lottTypeKey == 'k3'){
            $winnerMoney    = $v['num'] * $v['odds'] * $v['money_unit'] * $v['multiple'] * $v['eo_money'];
        }elseif ($lottTypeKey == 'ssc'){
            $winnerMoney    = $v['num'] * $v['odds'] * $v['money_unit'] * $v['multiple'];
        }elseif ($lottTypeKey == 'syxw'){
            $winnerMoney    = $v['num'] * $v['odds'] * $v['money_unit'] * $v['multiple'];
        }
        $tmp            = [];
        $tmp['uid']     =   $v['uid'];
        $tmp['tid']     =   'betting_award';
        $tmp['lkey']    =   'FZ' . $v['order_no'];
        $tmp['money']   =   $winnerMoney;
        $tmp['balance'] =   -$winnerMoney;
        $tmp['notes']   =   '彩票中奖：【' . $v['cn_play'] . ':' . $v['betting_no'] . '】';
        moneyLog($tmp);
        // 修改投注状态与返奖状态
        $sql = 'UPDATE ' . $dbprefix . 'lottery_order_item SET prize_status = 2, prize = ' . $winnerMoney . ' WHERE id = ' . $v['id'];
        $db->exec($sql);
        $orderPrize += $winnerMoney;
    }
    echo $orderPrize . '-' . $key . '<br/>';
    // 更新订单中奖信息
    $sql  = 'UPDATE ' . $dbprefix . 'lottery_order_main SET prize = ' . $orderPrize . ', status = 2 WHERE id = ' . $key;
    $flag = $db->exec($sql);
    var_dump($flag);
}

